/**
 * 存储sessionStorage
 */
export const setStore = (name, content) => {
  if (!name) return;
  if (typeof content !== 'string') {
    content = JSON.stringify(content);
  }
  sessionStorage.setItem(name, content);
};

/**
 * 获取sessionStorage
 */
export const getStore = name => {
  if (!name) return;
  return sessionStorage.getItem(name);
};

/**
 * 删除sessionStorage
 */
export const removeStore = name => {
  if (!name) return;
  sessionStorage.removeItem(name);
};

/**
 * 清空sessionStorage
 */
export const clearStore = () => {
  sessionStorage.clear();
};

/**
 * 将参数拼接为 GET请求的形式
 * @param {Object} postData
 * @return {String} url GET请求参数拼接的形式
 */
export const serializeUrl = (postData) => {
  let idx = 0, url = '';
  if (postData && postData !== '') {
    for (let key in postData) {
      if (idx === 0) {
        url += '?' + key + '=' + postData[key]
      } else {
        url += '&' + key + '=' + postData[key]
      }
      idx++
    }
  } else {
    url = "";
  }
  return url
};

/**
 * 获取地址栏参数
 * @param {String} name 参数名
 * @return {String} 返回参数值
 */
export const getQueryString = (name) => {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  let r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
};

/**
 * 删除对象空属性
 * @param {Object} param
 * @return {Object}
 */
export const deleteEmpty = function (param) {
  for (let key in param) {
    if (param[key] + '' !== '0') {
      if (!param[key] || param[key].length === 0 || param[key] === 'A') {
        delete param[key];
      } else {
        param[key].join ? param[key] = param[key].join(',') : '';
      }
    }
  }
  return param;
};

/**
 * 格式化时间
 * @param {Date} time
 * @param {String} fmt 格式eg: yyyy-MM-dd HH:mm:ss / yyyy年MM月dd日 EEE HH:mm:ss / EE(周一) / EEE(星期一)
 * @param {Boolean} fix 是否计算本地时间与GMT时间的时间差
 * @return {String} 返回fmt格式
 */
export const formatDate = (time, fmt, fix) => {
  if (!time) {
    return time;
  }
  let week = {
    '0': '日',
    '1': '一',
    '2': '二',
    '3': '三',
    '4': '四',
    '5': '五',
    '6': '六'
  };
  let offSet = 60 * 1000 * (new Date(0)).getTimezoneOffset();
  let date = null;
  offSet = !fix ? 0 : offSet;
  if (time instanceof Date) {
    date = time;
  } else {
    date = new Date(+time + offSet);
  }
  let o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': (date.getHours() % 12) === 0 ? 12 : (date.getHours() % 12), // 小时
    'H+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '星期' : '周') : '') + week[date.getDay() + ''])
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt;
};

/**
 * 将秒转换为时间
 * @param {String} sec 秒
 * @return {String} hh:mm:ss
 */
export const convertSecondToTime = sec => {
  if (sec === 0) {
    return sec;
  }
  let hh = 0;
  let mm = 0;
  let ss = 0;
  const step = 60;
  const fix = t => {
    return t < 10 ? '0' + t : t + '';
  };
  const timeOffset = (t, step) => {
    return [Math.floor(t / step), t % step];
  };
  [mm, ss] = timeOffset(sec, step);
  if (mm > 59) {
    [hh, mm] = timeOffset(mm, step);
  }
  return [fix(hh), fix(mm), fix(ss)].join(':');
};

/**
 * 格式化金钱
 * @param {Number} num 123455.32323
 * @return {String} 123,455.32323
 */
export const formatMoney = function (num) {
  if (typeof num != 'number') return num;
  let isNegative = false;
  if (num < 0) {
    isNegative = true;
  }
  num = Math.abs(num);
  let str = new String(num);
  let str0, str1;
  if (str.indexOf('.') != -1) {
    str0 = str.split('.')[0];
    str1 = '.' + str.split('.')[1];
  } else {
    str0 = str;
    str1 = '';
  }
  let arr = str0.split('');
  let sub = [];
  if (arr.length > 3) {
    let start = arr.length % 3;
    if (start != 0) sub.push(start);
    for (let i = 0; i < arr.length; i++) {
      if ((i + 1 - start != 0) && (i + 1 - start) % 3 == 0 && (i + 1) != arr.length) {
        sub.push(i + 1);
      }
    }
    sub.map((value, index) => {
      if (index != 0) {
        value += index;
      }
      arr.splice(value, 0, ',');
    });
    return (isNegative ? '-' : '') + arr.join('') + str1;
  } else {
    return (isNegative ? '-' : '') + num;
  }
};

/**
 * 根据最里层子元素的某个属性获取其父级某个属性的集合
 * @param {Array} array
 * @param {String} childAttr 最里层子元素的属性值
 * @param {String} attrName 匹配的属性名
 * @param {String} parentAttrName 需返回的父级属性名
 * @return {Array} 父级集合
 */
export const getParents = (array, childAttr, attrName, parentAttrName) => {
  let stack = [];
  let going = true;
  let walker = (array, childAttr) => {
    array.forEach(item => {
      if (!going) return;
      stack.push(item[parentAttrName]);
      if (item[attrName] === childAttr) {
        going = false;
      } else if (item['children']) {
        walker(item['children'], childAttr);
      } else {
        stack.pop();
      }
    });
    if (going) stack.pop();
  };
  walker(array, childAttr);
  return stack;
};

/**
 * 根据某个属性获取其它属性
 * @param {Array} data
 * @param {String} attrVal
 * @param {String} attrName
 * @param {String} needAttr 需要的属性的名
 * @return {String} 返回需要的属性值
 */
export const getCurrentData = (data, attrVal, attrName, needAttr) => {
  let name = "";
  let walker = (data, attrVal) => {
    data.forEach(item => {
      if (item[attrName] === attrVal) {
        name = item[needAttr];
      } else if (item['children']) {
        walker(item['children'], attrVal);
      }
    });
  };
  walker(data, attrVal);
  return name;
};
